﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

using MOJsdk;
using System.Collections.ObjectModel;
using System.Threading;
using System.Windows.Threading;
using io = System.IO;
using System.Web;
using System.Net;

namespace MOJ
{
    /// <summary>
    /// Interaction logic for Control_MovieSearch.xaml
    /// </summary>
    public partial class Control_MovieSearch : UserControl
    {
        public Control_MovieSearch()
        {
            InitializeComponent();
            INI();
        }

        #region INI
        private void INI()
        {
            INIControls();
            INIEvents();
        }
        private void INIControls()
        {
            _txtBox_query.Text = "";
            _btnSelect.Content = MOJLocalization.Localize("Select");

            _btnSelect.IsEnabled = false;
            _btnSearch.IsEnabled = false;

            #region Styles
            _Grid.ApplyStyle("0101001");
            _txtBox_query.ApplyStyle("0101002");
            _btnSelect.ApplyStyle("0101003");
            _btnSearch.ApplyStyle("0101004");
            _listView.ApplyStyle("0101005");

            #endregion
        }
        private void INIEvents()
        {
            OnMovieSelected += delegate { };
            OnClose += delegate { };

            _listView.SelectionChanged += SelectionChanged;
            _txtBox_query.TextChanged += TextChanged;
            _btnSearch.Click += Search;
            _txtBox_query.KeyDown += TextKeyDown;

            _btnSelect.Click += SelectMovie;
        }
        #endregion

        private void SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            _btnSelect.IsEnabled = _listView.SelectedIndex >= 0;
        }
        private void TextChanged(object sender, TextChangedEventArgs e)
        {
            int x = _txtBox_query.Text.Length;
            _btnSearch.IsEnabled = x > 2;
        }

        private ObservableCollection<MojWebMovie> _movies;
        private void TextKeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Return)
            {
                Search(null, null);
            }
        }
        private void Search(object sender, RoutedEventArgs e)
        {
            try
            {
                string query = _txtBox_query.Text;
                InternetInfo _webInfo = new InternetInfo(TOOLS.TMDB_APIKey);
                _webInfo.onError += ReportError;

                SetAvaible(false);

                _webInfo.onSearchMovieCompleted += SearchMovieComplete;
                _webInfo.SearchMovieAsync(query);
            }
            catch (Exception ex)
            {
                GlobalVars.TheHost.ReportError(new ErrorReporter()
                {
                    ErrorMessage = "Error searching movie",
                    ErrorDetails = ex.ToString(),
                    ErrorCode = "Search001",
                });
            }
        }

        private void ReportError(ErrorReporter Error)
        {
            GlobalVars.TheHost.ReportError(Error);
        }

        private void SearchMovieComplete(List<MojWebMovie> Results)
        {
            this.Dispatcher.BeginInvoke(DispatcherPriority.Send, (ThreadStart)delegate
            {
                _movies = new ObservableCollection<MojWebMovie>(Results);
                _listView.ItemsSource = _movies;
                SetAvaible(true);
            });
        }

        private void SearchImdbComplete(List<MojWebMovie> Results)
        {
            this.Dispatcher.BeginInvoke(DispatcherPriority.Send, (ThreadStart)delegate
            {
                SetAvaible(true);

                if (Results.Count == 1)
                {
                    OnMovieSelected(Results[0]);
                }
                else
                {
                    GlobalVars.TheHost.ShowMessage(MOJLocalization.Localize("Invalid IMDB id!"), 
                        MOJLocalization.Localize("Warning"));
                }
            });
        }

        private void SelectMovie(object sender, RoutedEventArgs e)
        {
            int x = _listView.SelectedIndex;
            if (x == -1) return;

            OnMovieSelected(_movies[x]);
            OnClose(this, new RoutedEventArgs());
        }

        private void SetAvaible(bool value)
        {
            _Grid.IsEnabled = value;
        }

        public delegate void MovieSelectHandler(MojWebMovie Movie);
        public event MovieSelectHandler OnMovieSelected;
        public event RoutedEventHandler OnClose;
    }
}
